//
//  DiaryViewController.m
//  PipeNote
//
//  Created by lanou3g on 15/12/18.
//  Copyright © 2015年 lanou3g. All rights reserved.
//

#import "DiaryViewController.h"
#import "SetViewController.h"
#import "WriteViewController.h"
#import "ShowDiaryViewController.h"
#import "RootViewController.h"
#import "Behavior.h"
#import "AppDelegate.h"
#import "Write.h"
#import "Photo1.h"
#import "Photo2.h"
#import "PhotoDiary.h"
static BOOL isTag = NO;
@interface DiaryViewController ()<UITableViewDataSource,UITableViewDelegate>
{
    UIImageView *imageView;
    UIButton *addButton;
    Behavior *behavior;
    NSTimer *timer;
}

@property (nonatomic,strong) NSMutableArray *array;
@property (nonatomic,strong) UITableView *tableView;
//@property (nonatomic,strong) Behavior *b;


@end

@implementation DiaryViewController

- (void)dealloc{
    
    //移除控制器所有通知
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}


//界面有变化时执行
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self viewDidLoad];
    //取出数据
    [self refreshData];
}

- (void)viewDidLoad {
   [super viewDidLoad];
  
    //背景图片
    [self background];
   
    
    [timer invalidate];
    timer = nil;
  //  计时器
   timer = [NSTimer scheduledTimerWithTimeInterval:0.7 target:self selector:@selector(addButtonAction) userInfo:nil repeats:YES];
    
    
    //写日记按钮
    [self addButton];
   
    //动画
    [self animation];
    
    //创建tableView
    if (ScreenFrame_Widdth == 320) {
        
        self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 200, self.view.frame.size.width, self.view.frame.size.height - 430) style:UITableViewStylePlain];
    }
    if (ScreenFrame_Widdth == 375) {
        
        self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 180, self.view.frame.size.width, self.view.frame.size.height - 460) style:UITableViewStylePlain];
    }
    if (ScreenFrame_Widdth == 414) {
        
        self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 180, self.view.frame.size.width, self.view.frame.size.height - 460) style:UITableViewStylePlain];
    }
    if (ScreenFrame_Height == 480) {
        
      self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 160, self.view.frame.size.width,130) style:UITableViewStylePlain];
    }
    
    self.tableView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.tableView];
    
    //遵守协议
    self.tableView.dataSource = self;
    self.tableView.delegate = self;

    
    //设置按钮
    [self set];
    //取出数据
    [self refreshData];
    
    //给下面的动画图片添加手势
    [self underAnimation];
    
   
    self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

//写日记按钮
- (void)addButton{

    
    if (ScreenFrame_Widdth == 320) {
        
         addButton = [[UIButton alloc] initWithFrame:CGRectMake(210,100,70,70)];
    }
    if (ScreenFrame_Widdth == 375) {
        
        addButton = [[UIButton alloc] initWithFrame:CGRectMake(240,100,80,80)];
    }
    if (ScreenFrame_Widdth == 414) {
        
        addButton = [[UIButton alloc] initWithFrame:CGRectMake(270,100,90,90)];
    }
    
    
    [addButton setBackgroundImage:[UIImage imageNamed:@"写.jpg"] forState:UIControlStateNormal];
    //    addButton.layer.cornerRadius = 50;
    [addButton addTarget:self action:@selector(mondayTuesday:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:addButton];
    
}



//设置按钮
- (void)set{
    
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"设置.png"] style:UIBarButtonItemStylePlain target:self action:@selector(leftItemAction:)];
    self.navigationItem.leftBarButtonItem = leftItem;
    
}

//设置按钮事件
- (void)leftItemAction:(UIBarButtonItem *)sender{
    
    SetViewController *setVC = [[SetViewController alloc] init];
    [self.navigationController pushViewController:setVC animated:YES];
    

}

//定时方法
- (void)addButtonAction{
    //转动图片
    addButton.transform = CGAffineTransformRotate(addButton.transform, M_PI/10);
    
}

//写日记
- (void)mondayTuesday:(UIButton *)sender{
    
    WriteViewController *writeVC = [[WriteViewController alloc] init];
    UINavigationController *writeNC = [[UINavigationController alloc] initWithRootViewController:writeVC];
    writeNC.modalTransitionStyle = 1;
    [self presentViewController:writeNC animated:YES completion:nil];
    
}

#pragma mark - 协议方法 - UITableViewDataSource
//设置每个分区的行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return self.array.count;
}
//创建cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    
    static NSString *str = @"y-y";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:str];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:str];
    }
    
    
    
    cell.backgroundColor = [UIColor clearColor];
    cell.textLabel.text = self.array[indexPath.row];
    
    return cell;
    
}



#pragma mark - 协议方法 - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    ShowDiaryViewController *showVC = [[ShowDiaryViewController alloc] init];
    UINavigationController *showNC = [[UINavigationController alloc] initWithRootViewController:showVC];
    showNC.modalTransitionStyle = 0;
    [self presentViewController:showNC animated:YES completion:nil];
    
    showVC.content = self.array[indexPath.row];
    
}

//取出数据
- (void)refreshData{
    
    AppDelegate *app = [UIApplication sharedApplication].delegate;
    self.array = [NSMutableArray array];
    //创建搜索请求对象，并且指明所有的数据类型
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Write"];
    NSArray *objcArray = [app.managedObjectContext executeFetchRequest:request error:nil];
    for (Write *write in objcArray) {
   
         [self.array addObject:write.content];
    }
 
    
    //刷新界面
    [self.tableView reloadData];
}


- (void)setEditing:(BOOL)editing animated:(BOOL)animated{
    [self.tableView setEditing:editing animated:animated];
    
    [super setEditing:editing animated:animated];
}

//删除数据
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSUInteger row = [indexPath row]; //获取当前行
    
  
    AppDelegate *app = [UIApplication sharedApplication].delegate;
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Write"];
    NSPredicate *cata = [NSPredicate predicateWithFormat:@"content = %@",self.array[row]];//获取当前行的内容(数据库中的)
    request.predicate = cata;
    NSArray *array = [app.managedObjectContext executeFetchRequest:request error:nil];
    
    for (Write *write in array) {
        [app.managedObjectContext deleteObject:write];
    }
    
    if ([app.managedObjectContext hasChanges]) {
        [app.managedObjectContext save:nil];
    }
    
    
    [self.array removeObjectAtIndex:row];//移除UI上当前行的cell
    [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];//数组执行删除操作
    
}

//动画
- (void)animation{
    

    behavior = [[Behavior alloc]initWithFrame:CGRectMake(-50.0f, self.view.frame.size.height-500.0f, 320.0f, self.view.frame.size.height - 200.0f)];
   

    if (ScreenFrame_Widdth == 320) {
        
        behavior = [[Behavior alloc]initWithFrame:CGRectMake(-10.0f, 180.0f, 350.0f, self.view.frame.size.height - 120.0f)];
    }
    
    if (ScreenFrame_Widdth == 375) {
        
        behavior = [[Behavior alloc]initWithFrame:CGRectMake(0.0f, 200.0f, 380.0f, self.view.frame.size.height - 120.0f)];
    }
    if (ScreenFrame_Widdth == 414) {
        
        behavior = [[Behavior alloc]initWithFrame:CGRectMake(-10.0f, 220.0f, 440.0f, self.view.frame.size.height - 120.0f)];
    }
    if (ScreenFrame_Height == 480) {
        
       behavior = [[Behavior alloc]initWithFrame:CGRectMake(-10.0f, 160, 340, self.view.frame.size.height - 120.0f)];
    }

    [behavior createBallsAndAnchors];
    [behavior applyDynamicBehaviors];
    [self.view addSubview:behavior];
   // [self underAnimation];
}

//手势
- (void)underAnimation{
   
    //给下面的动画图片添加手势
    longGR = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longGRAction)];
    longGR.numberOfTouchesRequired = 2;
    [self.view addGestureRecognizer:longGR];
   

    longGR1 = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longGR1Action)];
    [self.view addGestureRecognizer:longGR1];
    
}



- (void)longGRAction{
    
    isTag = NO;
    
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate = self;
    // 设置挑选出的图片是否可编辑
    picker.allowsEditing = YES;
    // 模态出图片库
    [self presentViewController:picker animated:YES completion:nil];
    
}

- (void)longGR1Action{
    
    isTag = YES;
    
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate = self;
    // 设置挑选出的图片是否可编辑
    picker.allowsEditing = YES;
    // 模态出图片库
    [self presentViewController:picker animated:YES completion:nil];
    
}
#pragma mark - 协议方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    
    if (isTag == NO) {
        
        AppDelegate *app = [UIApplication sharedApplication].delegate;
        
        //在添加新的照片之前删除原来的
        NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Photo1"];
        NSPredicate *cata = [NSPredicate predicateWithFormat:@"number>0"];//获取当前行的内容(数据库中的)
        request.predicate = cata;
        NSArray *array = [app.managedObjectContext executeFetchRequest:request error:nil];
        
        for (Photo1 *photo in array) {
            [app.managedObjectContext deleteObject:photo];
        }
        
        if ([app.managedObjectContext hasChanges]) {
            [app.managedObjectContext save:nil];
        }
        
        
        //添加新的照片
        self.imageData = UIImageJPEGRepresentation(image, 0.5);
        Photo1 *photo = [NSEntityDescription insertNewObjectForEntityForName:@"Photo1" inManagedObjectContext:app.managedObjectContext];
        photo.photo1 = self.imageData;
        
        photo.number = [NSString stringWithFormat:@"%@",self.imageData];
        
        //保存数据
        [app saveContext];
        
    }
    
    if (isTag == YES) {
        
        AppDelegate *app = [UIApplication sharedApplication].delegate;
        //在添加新的照片之前删除原来的
        NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Photo2"];
        NSPredicate *cata = [NSPredicate predicateWithFormat:@"number>0"];//获取当前行的内容(数据库中的)
        request.predicate = cata;
        NSArray *array = [app.managedObjectContext executeFetchRequest:request error:nil];
        
        for (Photo2 *photo in array) {
            [app.managedObjectContext deleteObject:photo];
        }
        
        if ([app.managedObjectContext hasChanges]) {
            [app.managedObjectContext save:nil];
        }
        
        
        //添加新的照片
        self.imageData = UIImageJPEGRepresentation(image, 0.5);
        Photo2 *photo = [NSEntityDescription insertNewObjectForEntityForName:@"Photo2" inManagedObjectContext:app.managedObjectContext];
        photo.photo2 = self.imageData;
        photo.number = [NSString stringWithFormat:@"%@",self.imageData];
        //保存数据
        [app saveContext];
 
        
        
    }
    
    [self viewDidLoad];

    [self dismissViewControllerAnimated:YES completion:nil];
    
}

- (void)background{
    
    imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@""]];
    imageView.frame = CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height-100);
    [self.view addSubview:imageView];
    
    
    AppDelegate *app = [UIApplication sharedApplication].delegate;
    
    //创建搜索请求对象，并且指明所有的数据类型
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"PhotoDiary"];
    NSArray *objcArray = [app.managedObjectContext executeFetchRequest:request error:nil];
    
    PhotoDiary *photo = objcArray.lastObject;
    
    UIImage *image = [UIImage imageWithData:photo.photo];
    imageView.image = image;
    
    if (objcArray.count == 0) {
        
        imageView.image = [UIImage imageNamed:@"日记背景.jpg"];
    }
    
}

@end
